package com.wenx.v3auth.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务发现测试控制器
 * 
 * @author wenx
 */
@Slf4j
@RestController
@RequestMapping("/test/discovery")
@RequiredArgsConstructor
public class ServiceDiscoveryController {

    private final DiscoveryClient discoveryClient;

    /**
     * 获取所有注册的服务
     */
    @GetMapping("/services")
    public Map<String, Object> getServices() {
        Map<String, Object> result = new HashMap<>();
        
        List<String> services = discoveryClient.getServices();
        result.put("services", services);
        
        log.info("发现的服务列表: {}", services);
        
        return result;
    }

    /**
     * 获取特定服务的实例信息
     */
    @GetMapping("/service/{serviceName}")
    public Map<String, Object> getServiceInstances(@PathVariable String serviceName) {
        Map<String, Object> result = new HashMap<>();
        
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        result.put("serviceName", serviceName);
        result.put("instanceCount", instances.size());
        result.put("instances", instances.stream().map(instance -> {
            Map<String, Object> instanceInfo = new HashMap<>();
            instanceInfo.put("instanceId", instance.getInstanceId());
            instanceInfo.put("host", instance.getHost());
            instanceInfo.put("port", instance.getPort());
            instanceInfo.put("uri", instance.getUri());
            instanceInfo.put("metadata", instance.getMetadata());
            return instanceInfo;
        }).toList());
        
        log.info("服务 {} 的实例信息: {}", serviceName, result);
        
        return result;
    }
} 